import survey

COST_DATA_DIR='./data'

def Mean(t):
	"""Computes the mean of a sequence of numbers.
	Args:
		t: sequence of numbers

	Returns:
		float
	"""
	return float(sum(t)) / len(t)

def PartitionRecords(table):
	"""Divides records into two lists: first babies and others.

	Only live births are included

	Args:
		table: pregnancy table
	"""
	firsts = survey.Pregnancies()
	others = survey.Pregnancies()

	for p in table.records:
		# skip non-live births
		if p.outcome != 1:
			continue

		if p.birthord == 1: # p.outcome == 1 && p.birthord == 1
			firsts.AddRecord(p)
		else: # p.outcome == 1 && p.birthord != 1
			others.AddRecord(p)

	return firsts, others

def FilterOutcome(table):
	"""Select the outcome of record  in the table.

	Args:
		table: pregnancy table

	Return:
		live births table
	"""
	liveBabies = survey.Pregnancies()
	for p in table.records:
		if p.outcome == 1:
			liveBabies.AddRecord(p)

	return liveBabies

def Process(table):
	""" Runs analysis on the given table.

	Args:
		table: table object
	"""
	table.lengths = [p.prglength for p in table.records]
	table.n = len(table.lengths)
	table.mu = Mean(table.lengths)

def MakeTables(data_dir=COST_DATA_DIR):
	"""Reads survey data and returns tables for first babies and others."""
	table = survey.Pregnancies()
	table.ReadRecords(data_dir)
	
	lives = FilterOutcome(table)
	firsts, others = PartitionRecords(lives)

	return table, lives,firsts, others

def ProcessTables(*tables):
	"""Processes a list of tables
	Args:
		tables: gathered argument tuple of Tuples
	"""
	for table in tables:
		Process(table)

def Summarize(data_dir):
	"""Prints summari statistics for first babies and others

	Returns:
		tuple of tables
	"""
	table, lives, firsts, others = MakeTables(data_dir)

	ProcessTables(lives,firsts,others)

	print 'Number of live babies', lives.n
	print 'Number of first babies', firsts.n
	print 'Number of others', others.n

	mu1, mu2 = firsts.mu, others.mu

	print 'Mean gestation in weeks:'
	print 'Lives babies', lives.mu
	print 'First babies', mu1
	print 'Others', mu2
	print 'First & Others', Mean([mu1,mu2])

	print 'Difference in days', (mu1 - mu2) * 7.0
	print 'Difference in hours', (mu1 - mu2) * 7.0 * 24

def main(name, data_dir=COST_DATA_DIR):
	Summarize(data_dir)

if __name__ == '__main__':
	import sys
	main(*sys.argv)